package com.zrfintech.manage.controller.mg;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrfintech.common.pojo.BasePageEntity;
import com.zrfintech.domain.MgRole;
import com.zrfintech.manage.pojo.PageResponse;
import com.zrfintech.manage.service.MgRoleService;
import com.zrfintech.manage.service.MgUserRoleService;
import com.zrfintech.manage.vo.request.RoleRequest;
import com.zrfintech.manage.vo.request.UserRoleRequest;
import com.zrfintech.manage.vo.response.AmisOption;
import com.zrfintech.service.MgRoleRepo;
import com.zrfintech.service.MgUserRoleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/webapi/role")
public class MgRoleController {

    @Autowired
    private MgRoleRepo mgRoleRepo;

    @Autowired
    private MgUserRoleRepo mgUserRoleRepo;

    @Autowired
    private MgRoleService roleService;

    @Autowired
    private MgUserRoleService userRoleService;

    @RequestMapping("/simpleList")
    public Object simpleList(BasePageEntity basePageEntity) {
        PageResponse<MgRole> pageResponse = new PageResponse<>();
        Page<MgRole> pageConfigPage = mgRoleRepo.pageList(basePageEntity);
        pageResponse.setItems(pageConfigPage.getRecords());
        pageResponse.setTotal(pageConfigPage.getTotal());
        return pageResponse;
    }

    @RequestMapping("/upsert")
    public Object upsert(@RequestBody RoleRequest mgRole) {
        roleService.upsert(mgRole, mgRole.getMenuCodeList(), mgRole.getOptionCodeList(), mgRole.getDataIdList());
        return new JSONObject();
    }

    @RequestMapping("/roleCodeListByUserCode")
    public Object roleCodeListByUserCode(String userCode) {
        List<String> userRoleCodeList = mgUserRoleRepo.getRoleCodeListByUserCode(userCode);
        JSONObject result = new JSONObject();
        result.put("userRoleCodeList", userRoleCodeList);
        return result;
    }

    @RequestMapping("/configRole")
    public Object configRole(@RequestBody UserRoleRequest userRoleRequest) {
        userRoleService.batchUpsert(userRoleRequest);
        return new JSONObject();
    }

    @RequestMapping("/getAll")
    public Object getAll() {
        List<MgRole> allList = mgRoleRepo.getAll();
        return allList.stream().map(item -> new AmisOption(item.getRoleName(), item.getRoleCode())).collect(Collectors.toList());
    }

}
